import gameManager from "./gameManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class uiManager extends cc.Component {
    @property([cc.Prefab])
    obstacle: cc.Prefab[] = []
    @property(cc.Prefab)
    star: cc.Prefab = undefined
    @property(cc.Label)
    timeTxt: cc.Label = undefined
    @property(gameManager)
    gameManager: gameManager = undefined


    private time = 1.5  //初始加载障碍物的时间

    onLoad() {
        this.init()
    }

    init() {
        this.loadobstacle() 
    }


    //加载障碍物
    private loadobstacle() {
        let n = Math.floor(Math.random() * 2 + 1)
        let isTop = Math.random() > 0.5 ? 1 : -1
        if (Math.floor(Math.random() * 9) === 1) {
            let star = cc.instantiate(this.star)
            star.x = cc.winSize.width / 2
            star.y = 0
            star.parent = this.node
        }
        for (let i = 0; i < n; i++) {
            if (i == 0) {
                let n = Math.floor(Math.random() * 4)
                let node = cc.instantiate(this.obstacle[n])
                node.x = cc.winSize.width / 2
                node.y = n == 3 ? (cc.winSize.height / 2) * isTop : (cc.winSize.height / 2 - node.height / 2) * isTop
                node.parent = this.node
                node.angle = isTop == 1 ? 180 : 0
            }
            else {
                let n = Math.floor(Math.random() * 4)
                let node = cc.instantiate(this.obstacle[n])
                node.x = cc.winSize.width / 2
                node.y = n == 3 ? (cc.winSize.height / 2) * isTop * -1 : (cc.winSize.height / 2 - node.height / 2) * isTop * -1

                node.parent = this.node
                node.angle = -isTop == 1 ? 180 : 0
            }
        }
    }





    update(dt) {
        this.time -= dt
        if (this.time <= 0 && !this.gameManager.isFail) {
            this.time = 1.5 - (+this.timeTxt.string / 100)
            if (this.time <= 1) this.time = 1
            this.loadobstacle()
        }
        if (this.gameManager.isFail) {
            this.node.removeAllChildren()
        }
    }

}
